package com.acmedcare.framework.exchange.center.jmx;

import com.acmedcare.framework.exchange.center.core.PluginContainerMBean;
import com.acmedcare.framework.exchange.center.core.exception.PluginNotFoundException;
import com.acmedcare.framework.exchange.center.core.handler.AgentHandlerMBean;
import com.acmedcare.framework.exchange.center.entity.bean.Plugin;
import com.acmedcare.framework.exchange.center.entity.bean.Task;
import java.util.ArrayList;
import java.util.List;
import javax.management.MBeanServerConnection;
import javax.management.MBeanServerInvocationHandler;
import javax.management.ObjectName;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class JmxServerTest {

  public static void main(String[] args) throws Exception {

    args = new String[]{"plugin-demo", "55485"};
    JmxServer.main(args);

    List<Plugin> plugins = new ArrayList<>();
    Plugin plugin = new Plugin();
    plugin.setPluginId(388732083841536L);
    plugin.setName("plugin-demo");
    plugin.setJarPath("http://192.168.1.159:18848/acmedcare-nas/nas/3,06dd66062553");
    plugin.setVersion("0.0.2");
    plugin.setDescription("测试自动装载插件");
    plugin.setJarName("exchange-center-plugin-demo-0.1.0.jar");
    plugin.setBasePackageName("com.acmedcare.framework.plugin.sample");
    plugin.setGroup_name("dev");
    plugin.setSpringBoot(true);
    plugins.add(plugin);
    createJmxConnection(plugins);
  }

  private static void createJmxConnection(List<Plugin> plugins) throws PluginNotFoundException {

    try {

      //等待5秒后创建桥接端链接
      Thread.sleep(5 * 1000L);
      String uri = String
          .format("service:jmx:rmi:///jndi/rmi://127.0.0.1:%s/jmxrmi", 55485);
      JMXServiceURL url = new JMXServiceURL(uri);
      MBeanServerConnection serverConnection = JMXConnectorFactory.connect(url, null)
          .getMBeanServerConnection();
      ObjectName mbeanName = new ObjectName("jmxBean:name=pluginContainer");

      log.info(String.format("插件：%s，桥接端正在创建链接......", "plugin-demo"));
      PluginContainerMBean proxy = MBeanServerInvocationHandler
          .newProxyInstance(serverConnection, mbeanName, PluginContainerMBean.class, false);

      AgentHandlerMBean agentHandlerMBean = MBeanServerInvocationHandler
          .newProxyInstance(serverConnection, new ObjectName("jmxBean:name=agentHandler"),
              AgentHandlerMBean.class, false);

      JmxServer.containerMBean.init(plugins);
      Task task = new Task();
      task.setName("demoagent");
      task.setPluginName("plugin-demo");
      task.setAgentName("com.acmedcare.framework.plugin.sample.data.DemoAgent");
    //  agentHandlerMBean.invoke(task);

    //  log.info("插件任务已经执行");
    } catch (Exception e) {

    }
  }
}
